<!-- prettier-ignore -->
<template>
  <div class="task-detail">
    <div class="detail-title">
      <div class="left">
        <div style="display: flex;flex-direction: column">
          <div>
            <i class="el-icon-arrow-left" style="font-size: 22px;font-weight: 900;cursor:pointer" @click="goBack"></i>
            <span class="task-name">【{{rowData?.name}}】地址质检</span>
          </div>
          <div v-if="rowData" class="detail-info">
            <span>创建人：{{rowData.user}}</span>
            <span>所属单位：{{rowData.unit}}</span>
            <span>创建时间：{{rowData.createTime}}</span>
            <span>范围：{{rowData.source}}</span>
          </div>
        </div>
        <el-button size="large" type="text" @click="showMap">{{isMapShow ? '关闭地图' : '开启地图'}}</el-button>
      </div>
      <div class="right">
        <div class="card">
          <div class="card-top">
            质检数量
          </div>
          <div class="card-bottom">
            <span class="number">{{rowData?.count}}</span>
            条
          </div>
        </div>
        <div class="aPartition"></div>
        <div class="card">
          <div class="card-top">
            通过数量
          </div>
          <div class="card-bottom">
            <span class="number">{{rowData?.pass}}</span>
            条
          </div>
        </div>
        <div class="aPartition"></div>
        <div class="card">
          <div class="card-top">
            未通过数量
          </div>
          <div class="card-bottom">
            <span class="number">{{rowData?.unpass}}</span>
            条
          </div>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="query-box">
        <template v-if="!isMapShow">
          <el-button size="small" type="primary" @click="pushAdress">推送问题地址</el-button>
          <el-button size="small" style="margin-right: 10px" type="primary" @click="exportReport(rowData)">下载质检报告</el-button>
          <el-input placeholder="统一标准地址" size="small" style="width: 300px;margin-right:10px">
            <el-button slot="append" icon="el-icon-search" type="primary"></el-button>
          </el-input>
          <el-radio-group v-model="filterCriteria" @input="radioChange">
            <el-radio label="all">全部</el-radio>
            <el-radio label="adopt">已通过</el-radio>
            <el-radio label="notAdopt">未通过</el-radio>
          </el-radio-group>
        </template>
        <template v-else>
          <div style="display: flex;align-items: center">
            <el-select v-model="selectOption" size="small">
              <el-option label="全部（17项质检问题）" value="all"></el-option>
              <el-option v-for="(item,index) in problemOptions" :key="index" :label="item.label" :value="item.label"></el-option>
            </el-select>
            <span style="margin-left: 10px;color: #6e6e6e">问题地址总数量：{{rowData?.unpass}}条</span>
          </div>
        </template>
      </div>
      <div class="detail-content">
        <div ref="listBox" class="list-box">
          <el-table :data="detailTable" :max-height="tableHandle? '560':'300'" header-row-class-name="table-header" highlight-current-row
                    row-class-name="row-class" size="mini" stripe @row-click="detailRowClick">
            <el-table-column align="center" type="selection" width="55">
            </el-table-column>
            <el-table-column align="center" fixed="left" label="序号" type="index" width="50"></el-table-column>
            <el-table-column align="center" fixed="left" label="统一标准地址" min-width="300" prop="tydzmc">
              <template slot-scope="{row}">
                <span :style="{color: (row.red && row.red.indexOf('tydzmc') > -1) ? 'red':''}">{{row.tydzmc}}</span>
              </template>
            </el-table-column>
            <template v-if="tableHandle">
              <el-table-column v-for="(item,index) in tableColumn" :key="index" :label="item.label" :prop="item.prop"
                               :width="['tysbdm'].includes(item.prop) ? '180': '120'" align="center" show-overflow-tooltip>
                <template slot-scope="{row}">
                  <div :style="{color: (row.red && row.red.indexOf(item.prop) > -1) ? 'red':''}">
                    <span v-if="row[item.prop]">{{row[item.prop]}}</span>
                    <span v-else-if="item.prop !== 'xqmc' && item.prop !== 'jzw'" style="color:red">*</span>
                  </div>
                </template>
              </el-table-column>
            </template>
            <template v-if="!isMapShow">
              <el-table-column align="center" fixed="right" label="质检结果">
                <template slot-scope="{row}">
                  <span v-if="row['f17']" style="color: red">未通过</span>
                  <span v-else style="color:#67c23a">通过</span>
                </template>
              </el-table-column>
              <el-table-column align="center" fixed="right" label="问题数量">
                <template slot-scope="{row}">
                  <span v-if="row['f17']">{{row['f17'].split('\n').length}}</span>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="问题描述" prop="f17" width="300">
                <template slot-scope="{row}">
                  <div style="white-space: pre-wrap">{{row['f17']}}</div>
                </template>
              </el-table-column>
            </template>
          </el-table>
          <el-pagination :page-size="resultQuery.size" :total="total" background layout="total,prev, pager, next" style="text-align: right;margin-top: 12px" @current-change="pageChange"></el-pagination>

          <!--展示选中项的详情-->
          <div v-if="!tableHandle && clickDetail">
            <p>地址质检详情</p>
            <wp-scrollbar :maxHeight="210" scrollbarColor="rgba(51, 51, 51, 0.3)">
              <el-descriptions v-if="clickDetail['f17']" :column="1" border labelClassName="detail-label" style="margin-bottom:10px">
                <el-descriptions-item label="问题描述">
                  <span style="white-space: pre-wrap">{{clickDetail['f17']}}</span>
                </el-descriptions-item>
              </el-descriptions>
              <el-descriptions :column="2" border labelClassName="detail-label">
                <template v-for="(value,key) in clickDetail">
                  <el-descriptions-item  v-if="dictionaryTable[key]" :key="key" :label="dictionaryTable[key]">
                    <span style="white-space: pre-wrap">{{value}}</span>
                  </el-descriptions-item>
                </template>
              </el-descriptions>
            </wp-scrollbar>
          </div>
        </div>
        <div v-if="!tableHandle" class="map-box">
          <cesium-map @mapFinish="mapReady"></cesium-map>
          <div class="legend">
            <p style="text-align: center">图例</p>
            <div>
              <img :src="require('@/assets/images/map/ding-pink.png')" alt="">
              <span>信息缺失或重复</span>
            </div>
            <div>
              <img :src="require('@/assets/images/map/ding-yellow.png')" alt="">
              <span>信息一致性问题</span>
            </div>
            <div>
              <img :src="require('@/assets/images/map/ding-orange.png')" alt="">
              <span>信息合规性问题</span>
            </div>
            <div>
              <img :src="require('@/assets/images/map/ding-blue.png')" alt="">
              <span>信息有效性问题</span>
            </div>
          </div>
          <div ref="blueBox" class="popup-div">
            <img :src="require('@/assets/images/map/ding-blue.png')" alt="">
          </div>
          <div ref="orangeBox" class="popup-div">
            <img :src="require('@/assets/images/map/ding-orange.png')" alt="">
          </div>
          <div ref="pinkBox" class="popup-div">
            <img :src="require('@/assets/images/map/ding-pink.png')" alt="">
          </div>
          <div ref="yellowBox" class="popup-div">
            <img :src="require('@/assets/images/map/ding-yellow.png')" alt="">
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

import cesiumMap from '@/components/cesiumMap/index.vue';
import {addOverlay, removePopup} from '@/utils/map';
import rulesJson from '@/assets/rules.json'
export default {
  name: "quality-test-detail",
  props:{
    rowData:{
      type:Object,
      default:null
    }
  },
  data(){
    return{
      selectOption:'all',
      filterCriteria:'all',
      isAll:true,
      total:0,
      listWidth:'100%',
      isMapShow: false,
      tableColumn:[
        {
          label:'省',
          prop:'shengmc'
        },
        {
          label:'市',
          prop: 'shimc'
        },
        {
          label:'区（县）',
          prop:'qumc'
        },
        {
          label:'街道',
          prop:'jdmc'
        },
        {
          label:'社区',
          prop:'sqmc'
        },
        {
          label:'道路',
          prop:'dlmc'
        },
        {
          label:'门牌号',
          prop:'mph'
        },
        {
          label:'小区',
          prop:'xqmc'
        },
        {
          label:'建筑物',
          prop:'jzw'
        },
        {
          label:'楼牌号',
          prop:'ldmc'
        },
        {
          label:'单元',
          prop:'dyh'
        },
        {
          label:'楼层',
          prop:'floor'
        },
        {
          label:'户室',
          prop:'fjhm'
        },
        {
          label:'所属社区代码',
          prop:'shequdm'
        },
        {
          label:'统一地址编码',
          prop:'tysbdm'
        }
      ],
      showColumn:[],
      tableHandle:true,
      queryHandle:true,
      detailTable:[],
      clickDetail:null,
      dictionaryTable:{
        tydzmc:'统一标准地址',
        shengmc:'省',
        shimc:'市',
        qumc:'县（区）',
        jdmc:'街道（乡镇）',
        sqmc: '社区',
        dlmc:'道路',
        mph:'门牌号',
        xqmc:'小区',
        jzw:'建筑物',
        ldmc:'楼牌号',
        dyh:'单元',
        floor:'楼层',
        fjhm:'户室',
        shequdm:'行政区划编码',
        tysbdm:'统一地址编码',
        lon: '经度',
        lat: '纬度'
      },
      problemOptions:[],
      resultQuery:{
        id:'',
        'f17':'',
        page:1,
        size: 10
      },
    }
  },
  created(){
    this.resultQuery.id = this.$route.params.id
    this.getResults()
  },
  mounted(){
    this.overlayList = []
    this.problemOptions = rulesJson.qualityTest
  },
  components:{cesiumMap},
  methods:{
    exportReport(data){
      // 下载文件
      const link = document.createElement('a');
      link.style.display = 'none';
      // 设置下载地址
      link.setAttribute('href', window.qualityTestUrl);
      // 设置文件名
      link.setAttribute('download', data.name + '_质检报告.pdf');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    radioChange(val){
      switch (val){
        case 'all':
          delete this.resultQuery.status
          break
        case 'adopt':
          this.resultQuery.status = 2
          break
        case 'notAdopt':
          this.resultQuery.status = 1
          break
        default:
          break
      }
      this.resultQuery.page = 1
      this.getResults()
    },
    pageChange(pageNum){
      this.resultQuery.page = pageNum
      this.getResults()
    },
    pushAdress(){
      this.$confirm('是否推送所选问题地址','提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        setTimeout(() => {
          loading.close();
          this.$message.success('问题地址推送成功')
        }, 1000);
      })
    },
    editThis(index){
      this.$set(this.detailTable,index,{...this.detailTable[index],isEdit:true})
    },
    confirmThis(index){
      this.$set(this.detailTable,index,{...this.detailTable[index],isEdit:false})
    },
    // 查看详情
    detailRowClick(row){
      if (this.isMapShow){
        this.clickDetail = row
        if (row['f17']){
          this.viewer.camera.setView({
            destination:Cesium.Cartesian3.fromDegrees(row.lon, row.lat, 200)
          })
        }
        this.overlayList.forEach(item=>{
          if (item.id === row.id){
            item.element.classList.add('icon-animation')
          } else {
            item.element.classList.remove('icon-animation')
          }
        })
      }
    },
    // 返回
    goBack(){
      this.$router.go(-1)
    },
    showMap(){
      this.removeAllOverlay()
      this.isMapShow = !this.isMapShow
      this.$refs.listBox.classList.remove('hide-map-animation')
      this.$refs.listBox.classList.remove('show-map-animation')
      if (this.isMapShow){
        this.queryHandle = false
        this.$refs.listBox.classList.add('show-map-animation')
        setTimeout(()=>{
          this.resultQuery.page = 1
          this.resultQuery.status = 1
          this.getResults()
          this.tableHandle = false
        },1000)
      } else {
        this.tableHandle = true
        this.$refs.listBox.classList.add('hide-map-animation')
        setTimeout(()=>{
          this.queryHandle = true
          this.resultQuery.page = 1
          delete this.resultQuery.status
          this.getResults()
        },1000)
      }
    },
    // 地图加载完毕，加载浮云框
    mapReady(){
      this.viewer = this.Global.viewer
      this.initLocation()
    },
    // 加载定位点
    async initLocation(){
      const res = await axios.get(`${window.baseUrl}/address/check/getResult`,{
        params:{
          ...this.resultQuery,
          status: 1,
          size:100
        }
      })
      const allProblem = res.data.data.records
      allProblem.forEach(item=>{
        if (item['f17']){
          const dom = this.getDomFromCondition(item)
          if (dom){
            if (item.tydzmc){
              dom.title = item.tydzmc
            }
            var cartographic = new Cesium.Cartographic(
              Cesium.Math.toRadians(item.lon), // 经度，转换为弧度
              Cesium.Math.toRadians(item.lat),  // 纬度，转换为弧度
              0                            // 高度
            );
            var cartesian = this.viewer.scene.globe.ellipsoid.cartographicToCartesian(cartographic);
            const overlay = addOverlay(this.viewer,dom,cartesian,-16,-32)
            overlay.show()
            overlay.id = item.id
            console.log(overlay);
            this.overlayList.push(overlay)
          }
        }
      })
      this.viewer.camera.setView({
        destination:Cesium.Cartesian3.fromDegrees(this.detailTable[0].lon, this.detailTable[0].lat, 5000)
      })
    },
    // 根据条件获取popup的dom
    getDomFromCondition(data){
      const rule = {
        '信息缺失或重复':'pink',
        '信息一致性问题':'yellow',
        '信息合规性问题':'orange',
        '信息有效性问题':'blue'
      }
      let dom = null
      rulesJson.qualityTest.forEach(item=>{
        if (data['f17'].indexOf(item.label) > -1){
          dom = this.$refs[`${rule[item.type]}Box`].cloneNode(true)
        }
      })
      return dom
    },
    // 移除所有浮云框
    removeAllOverlay(){
      removePopup(this.overlayList)
      this.overlayList = []
    },
    async getResults(){
      const res = await axios.get(`${window.baseUrl}/address/check/getResult`,{
        params:this.resultQuery
      })
      this.detailTable = res.data.data.records
      this.total = res.data.data.total
    }
  },
  beforeDestroy(){
    this.removeAllOverlay()
  }
};
</script>

<style lang="less" scoped>
.task-detail {
  width: 100%;
  height: 100%;
  .detail-title {
    width: 100%;
    height: 118px;
    margin-bottom: 12px;
    border-radius: 8px;
    background: url(~@/assets/images/addressSegment/detail-title-bg.png)
    no-repeat;
    background-origin: content-box;
    background-position: 50% 28%;
    background-size: 110% 110%;
    display: flex;
    .left {
      width: 65%;
      height: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 40px;
      .task-name {
        font-size: 22px;
        color: #333333;
      }
      .detail-info {
        display: flex;
        justify-content: space-around;
        margin-top: 10px;
        width: 810px;
      }
    }
    .right {
      width: 35%;
      height: 100%;
      padding: 0 40px;
      display: flex;
      align-items: center;
      justify-content: space-around;
      .aPartition {
        width: 1px;
        height: 51px;
        border: 1px solid #ffffff;
        opacity: 0.2;
      }
      .card {
        width: auto;
        height: 63px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        &-top {
          font-size: 16px;
          color: #fff;
        }
        &-bottom {
          font-size: 16px;
          color: #fff;
          vertical-align: bottom;
          .number {
            font-size: 24px;
            font-weight: 900;
            font-style: italic;
          }
        }
      }
    }
  }
  .content{
    width: 100%;
    height: calc(100% - 130px);
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    .query-box{
      margin-bottom: 10px
    }
    .detail-content {
      height: calc(100% - 35px);
      display: flex;
      .list-box {
        width: 100%;
        height: 100%;
      }
      .show-map-animation {
        width: 50%;
        animation: shrink 1s;
      }
      .hide-map-animation {
        width: 100%;
        animation: expand 1s;
      }
      @keyframes expand {
        from {
          width: 50%; /* 动画开始时的宽度 */
        }
        to {
          width: 100%; /* 动画结束时的宽度 */
        }
      }
      @keyframes shrink {
        from {
          width: 100%; /* 动画开始时的宽度 */
        }
        to {
          width: 50%; /* 动画结束时的宽度 */
        }
      }
      .map-box {
        width: 50%;
        height: 100%;
        padding-left: 20px;
        position:relative;
        .legend{
          width:auto;
          height:auto;
          padding: 10px;
          padding-top:0;
          background: #fff;
          position:absolute;
          bottom: 5px;
          right: 5px;
          z-index: 30;
          div{
            margin:5px 0;
            display: flex;
            align-items: center;
            img{
              width: 18px;
              height: 18px;
            }
          }
        }
      }
    }
  }
}
</style>
<style lang="less">
.icon-animation{
  img{
    position:relative;
    animation: imgAnimation 0.6s infinite;
  }
}
@keyframes imgAnimation {
  0% {
    top: 0
  }
  50%{
    top: -5px
  }
  100%{
    top: 0
  }
}
.row-class{
  cursor:pointer
}
.popup-div{
  width: 32px;
  height:32px;
  display: none;
  position: absolute;
  cursor:pointer;
}
.detail-label{
  width: 105px !important
}
</style>
